package com.lry.server;

import com.lry.proto.ClassInfo;
import com.lry.proto.Request;
import com.lry.proto.Response;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/9/16
 */
@Slf4j
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private static ExecutorService executorService= Executors.newFixedThreadPool(10);
    private List<Object> services;

    public ServerHandler(List<Object> services) {
        this.services = services;
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = (Request) msg;

                    log.info("服务器收到："+request);

                    ClassInfo classInfo= request.getClassInfo();
                    String uuid = request.getUuid();

                    for (Object service : services) {
                        if(classInfo.getClassName().equals(service.getClass().getInterfaces()[0].getName())){

                            Method method = service.getClass().getMethod(classInfo.getMethodName(), classInfo.getParamsTypeArr());
                            Object invoke = method.invoke(service, classInfo.getParamsArr());
                            log.info("服务器写给客户端："+invoke);
                            ctx.channel().writeAndFlush(new Response(uuid,invoke));
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.toString());
        super.exceptionCaught(ctx, cause);
    }
}


